import hashlib
import json
import requests
import pandas as pd
import os
to_csv_name = 'ultimate.csv'
to_csv_path = os.path.join(os.path.abspath(
    os.path.join(os.path.join(os.path.dirname(__file__), ".."), 'static/spider/data')),
    to_csv_name)
old_pd = pd.read_csv(to_csv_path, encoding='gbk')
pd_datas = pd.read_csv(to_csv_path, encoding='gbk').to_dict(orient='record')


def str_to_ll(address):
    # 腾讯位置服务API key和SecretKey
    key = 'HM3BZ-CGWNS-QF5OZ-6R3OK-ZHKP2-PSBR7'
    sk = 'tjikykqZaCEMOQzHD7B468Wky107qS2'

    # Web Service API接口路径
    path = '/ws/geocoder/v1'

    # 接口请求参数
    params = {
        'address': address,
        'key': key
    }
    # 将参数按照key进行升序排序
    params_sorted = sorted(params.items(), key=lambda x: x[0])
    # 拼接参数字符串
    param_str = '&'.join([f"{k}={v}" for k, v in params_sorted])
    # 计算签名
    sig_str = path + '?' + param_str + sk
    sig = hashlib.md5(sig_str.encode('utf-8')).hexdigest()
    # 构造最终请求URL
    url = f"https://apis.map.qq.com{path}?{param_str}&sig={sig}"
    # 发送请求并获取响应结果
    try:
        response = requests.get(url)
    except:
        proxies = {
            'https': '127.0.0.1:7890'
        }
        response = requests.get(url=url, proxies=proxies)
    result = json.loads(response.content)
    return [result['result']['location']['lng'], result['result']['location']['lat']]

locations = []
for index in range(13617):
    try:
        if index <= 9000:
            pd_data = pd_datas[index]
            location = str_to_ll(pd_data['地址'])
        else:
            location = []
    except:
        pd_data = pd_datas[index]
        print('index: ', index, '地址: ', pd_data['地址'])
        location = []
    locations.append(location)

new_pd = old_pd.assign(经纬度=locations)
# df_concat = pd.concat([old_pd, new_pd], axis=0)
to_csv_name = 'new_ultimate.csv'
to_csv_path = os.path.join(os.path.abspath(
    os.path.join(os.path.join(os.path.dirname(__file__), ".."), 'static/spider/data')),
    to_csv_name)
pd.to_csv(to_csv_path, encoding='utf-8')
print(new_pd)




